<template>
	<view class="content">
		<view class="search-box">
			<!-- mSearch组件 如果使用原样式，删除组件元素-->
			<mSearch class="mSearch-input-box" :mode="2" button="inside" :placeholder="defaultKeyword" @search="doSearch(false)" @input="inputChange" @confirm="doSearch(false)" v-model="keyword"></mSearch>
			
			 <!-- 原样式 如果使用原样式，恢复下方注销代码 -->
						
			<!-- <view class="input-box">
				<input type="text" :placeholder="defaultKeyword" @input="inputChange" v-model="keyword" @confirm="doSearch(false)"
				 placeholder-class="placeholder-class" confirm-type="search">
			</view> 
			<view class="search-btn" @tap="doSearch(false)">搜索</view> 
			-->
			<!-- 原样式 end -->
		</view>
		<view class="search-keyword" @touchstart="blur">
			<!-- <scroll-view class="keyword-list-box" v-show="isShowKeywordList" scroll-y>
				<view class="keyword-entry" hover-class="keyword-entry-tap" v-for="row in keywordList" :key="row.keyword">
					<view class="keyword-text" @tap="doSearch(row.keyword)">
						<rich-text :nodes="row.htmlStr"></rich-text>
					</view>
					<view class="keyword-img" @tap="setkeyword(row)">
						<image src="/static/HM-search/back.png"></image>
					</view>
				</view>
			</scroll-view> -->
			<!-- <scroll-view class="keyword-box" v-show="!isShowKeywordList" scroll-y>
				<view class="keyword-block" v-if="oldKeywordList.length>0">
					<view class="keyword-list-header">
						<view>历史搜索</view>
						<view>
							<image @tap="oldDelete" src="/static/HM-search/delete.png"></image>
						</view>
					</view>
					<view class="keyword">
						<view v-for="(keyword,index) in oldKeywordList" @tap="doSearch(keyword)" :key="index">{{keyword}}</view>
					</view>
				</view>
				<view class="keyword-block">
					<view class="keyword-list-header">
						<view>热门搜索</view>
						<view>
							<image @tap="hotToggle" :src="'/static/HM-search/attention'+forbid+'.png'"></image>
						</view>
					</view>
					<view class="keyword" v-if="forbid==''">
						<view v-for="(keyword,index) in hotKeywordList" @tap="doSearch(keyword)" :key="index">{{keyword}}</view>
					</view>
					<view class="hide-hot-tis" v-else>
						<view>当前搜热门搜索已隐藏</view>
					</view>
				</view>
			</scroll-view> -->
			<view :class="banner.display.layout || 'list'">
				<view class="item" v-for="(it, idx) in items.list" :key="idx" @click="goDetail(it)">
					<view class="cover">
						<view class="wp ratio3_4">
							<image class="image img-show" mode="widthFix" style="width: 100%;" :src="it.cover.url || it.cover.large"></image>
						</view>
					</view>
					<view class="info">
						<view class="h4"></view>
						<view class="h3">{{it.title}}</view>
						<view v-if="it.ratingValue" class="rank">
							<rating :count="it.ratingValue || 0" />
							<text>{{it.ratingValue}}</text>
						</view>
						<view class="meta">
							{{it.cardSubtitle}}
						</view>
						<view class="cite">{{it.description}}</view>
					</view>
				</view>
			</view>
			<!-- <Loading13></Loading13> -->
			<w-loading text=" " mask="true" click="false" ref="loading"></w-loading>
		</view>
	</view>
</template>

<script>
	import rating from "@/components/uni-rating-start/uni-rating-start.vue"
	
	let api = require("@/utils/api.js")
	//引用mSearch组件，如不需要删除即可
	import mSearch from '@/components/uni-search/uni-search.vue'
	export default {
		data() {
			return {
				defaultKeyword: "请输入书名或作者名",
				keyword: "",
				oldKeywordList: [],
				hotKeywordList: [],
				keywordList: [],
				forbid: '',
				isShowKeywordList: false,
				banner: {id: -1},
				items: {
					list: [],
					loading: false,
					page: {page: 1, size: 12}
				},
				tempItems: [],
				collections: ['book_top250', 'book_classic', 'book_fiction', 'book_film_original',
					'book_hot', 'book_latest', 'book_nonfiction', 'book_score']
			}
		},
		onLoad() {
			this.init();
		},
		components: {
			mSearch,
			rating,
		},
		methods: {
			init() {
				this.loadDefaultKeyword();
				this.loadOldKeyword();
				this.loadHotKeyword();
				this.banner.id = this.collections[this.banner.id = Math.floor(Math.random() * this.collections.length)];
				// 重置分页参数
				this.tempItems = [];
				this.items.list = [];
				this.items.page.page = 1;
				this.getCollectionDetail();
				this.getItems()
			},
			find(keyword) {
				var that = this;
				if(that.items.loading)
					return;
				var url = api.db_find;
				that.items.loading = true;
				this.$refs.loading.open();
				if(that.tempItems.length > 0) {
					that.items.list = that.items.list.concat(that.tempItems);
					// 置空临时数组
					that.tempItems = [];
					that.items.page.page++;
					that.items.loading = false;
					this.$refs.loading.close();
					// 加载下一页数据，存放在临时数组中
					setTimeout(function() {that.getTempItems(url, that.items.page.page)}, 100);
				}else{
					var params = Object.assign({'keyword': that.keyword}, that.items.page)
					uni.request({
						url: url,
						data: params,
						success: (res) => {
							if (res.statusCode == 200 && res.data.status == 'ok') {
								var data = res.data.data;
								if(!data || !data.list || data.list.length == 0){
									return;
								}
								data.list.forEach(d => {
									d.cover = that.getJSONByStr(d.pic, {})
								})
								if(data.isFirstPage)
									that.items.list = data.list;
								else
									that.items.list = that.items.list.concat(data.list);
								that.items.page.page++;
								// 加载下一页数据，存放在临时数组中
								setTimeout(function() {that.getTempItems(url, that.items.page.page)}, 100);
							}
						}, complete: () => {that.items.loading = false;this.$refs.loading.close();}
					});
				}
			},
			getCollectionDetail() {
				var that = this;
				uni.request({
					url: api.db_collection + that.banner.id,
					success: (res) => {
						if (res.statusCode == 200 && res.data.status == 'ok') {
							if(!res.data || !res.data.data){
								that.showNoDataErr = true;
								return;
							}
							that.banner = res.data.data;
							that.banner.display = that.getJSONByStr(that.banner.display, {layout: 'cardlist'})
						} else {
							that.showNoDataErr = true;
							return;
						}
					},
					complete: ()=>{uni.stopPullDownRefresh();}
				});
			},
			getItems() {
				var that = this;
				if(that.items.loading)
					return;
				var url = api.db_collection_item + that.banner.id;
				that.items.loading = true;
				this.$refs.loading.open();
				if(that.tempItems.length > 0) {
					that.items.list = that.items.list.concat(that.tempItems);
					// 置空临时数组
					that.tempItems = [];
					that.items.page.page++;
					that.items.loading = false;
					this.$refs.loading.close();
					// 加载下一页数据，存放在临时数组中
					setTimeout(function() {that.getTempItems(url, that.items.page.page)}, 100);
				}else{
					uni.request({
						url: url,
						data: that.items.page,
						success: (res) => {
							if (res.statusCode == 200 && res.data.status == 'ok') {
								var data = res.data.data;
								if(!data || !data.list || data.list.length == 0){
									return;
								}
								data.list.forEach(d => {
									d.cover = that.getJSONByStr(d.cover, {})
								})
								if(data.isFirstPage)
									that.items.list = data.list;
								else
									that.items.list = that.items.list.concat(data.list);
								that.items.page.page++;
								// 加载下一页数据，存放在临时数组中
								setTimeout(function() {that.getTempItems(url, that.items.page.page)}, 100);
							}
						}, complete: () => {that.items.loading = false;this.$refs.loading.close();}
					});
				}
			},
			getTempItems(url, pageNo) {
				var that = this;
				uni.request({
					url: url,
					data: {page: pageNo, size: that.items.page.size, 'keyword': that.keyword},
					success: (res) => {
						if (res.statusCode == 200 && res.data.status == 'ok') {
							var data = res.data.data;
							if(!data || !data.list || data.list.length == 0){
								return;
							}
							data.list.forEach(d => {
								d.cover = that.getJSONByStr(d.cover || d.pic, {})
							})
							that.tempItems = data.list;
						}
					}
				});
			},
			onReachBottom(event){
				if(this.keyword)
					this.find();
				else
					this.getItems();
			},
			goDetail(detail) {
				var param = {id: detail.subjectId || detail.id, title: detail.title, author:detail.author, ratingValue:detail.ratingValue, cardSubtitle: detail.cardSubtitle};
				uni.navigateTo({
					url: '/pages/book/detail/detail?query=' + encodeURIComponent(JSON.stringify(param))
				});
			},
			getJSONByStr(str, defaultVal){
				try {
					return JSON.parse(str);
				} catch (error) {
					console.log(error)
				}
				return defaultVal;
			},
			blur(){
				uni.hideKeyboard()
			},
			//加载默认搜索关键字
			loadDefaultKeyword() {
				//定义默认搜索关键字，可以自己实现ajax请求数据再赋值,用户未输入时，以水印方式显示在输入框，直接不输入内容搜索会搜索默认关键字
				//this.defaultKeyword = "";
			},
			//加载历史搜索,自动读取本地Storage
			loadOldKeyword() {
				uni.getStorage({
					key: 'OldKeys',
					success: (res) => {
						var OldKeys = JSON.parse(res.data);
						this.oldKeywordList = OldKeys;
					}
				});
			},
			//加载热门搜索
			loadHotKeyword() {
				//定义热门搜索关键字，可以自己实现ajax请求数据再赋值
				this.hotKeywordList = ['键盘', '鼠标', '显示器', '电脑主机', '蓝牙音箱', '笔记本电脑', '鼠标垫', 'USB', 'USB3.0'];
			}, 
			//监听输入
			inputChange(event) {
				//兼容引入组件时传入参数情况
				var keyword = event.detail?event.detail.value:event;
				if (!keyword) {
					this.keywordList = [];
					this.isShowKeywordList = false;
					this.init();
					return;
				}
				this.isShowKeywordList = true;
				//以下示例截取淘宝的关键字，请替换成你的接口
				// uni.request({
				// 	url: 'https://suggest.taobao.com/sug?code=utf-8&q=' + keyword, //仅为示例
				// 	success: (res) => {
				// 		this.keywordList = this.drawCorrelativeKeyword(res.data.result, keyword);
				// 	}
				// });
			},
			//高亮关键字
			drawCorrelativeKeyword(keywords, keyword) {
				var len = keywords.length,
					keywordArr = [];
				for (var i = 0; i < len; i++) {
					var row = keywords[i];
					//定义高亮#9f9f9f
					var html = row[0].replace(keyword, "<span style='color: #9f9f9f;'>" + keyword + "</span>");
					html = '<div>' + html + '</div>';
					var tmpObj = {
						keyword: row[0],
						htmlStr: html
					};
					keywordArr.push(tmpObj)
				}
				return keywordArr;
			},
			//顶置关键字
			setkeyword(data) {
				this.keyword = data.keyword;
			},
			//清除历史搜索
			oldDelete() {
				uni.showModal({
					content: '确定清除历史搜索记录？',
					success: (res) => {
						if (res.confirm) {
							console.log('用户点击确定');
							this.oldKeywordList = [];
							uni.removeStorage({
								key: 'OldKeys'
							});
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			//热门搜索开关
			hotToggle() {
				this.forbid = this.forbid ? '' : '_forbid';
			},
			//执行搜索
			doSearch(key) {
				//key = key ? key : this.keyword ? this.keyword : this.defaultKeyword;
				key = key ? key : this.keyword ? this.keyword : '';
				this.keyword = key;
				this.saveKeyword(key); //保存为历史 
				
				// 重置分页参数
				this.tempItems = [];
				this.items.list = [];
				this.items.page.page = 1;
				this.find();
			},
			//保存关键字到历史记录
			saveKeyword(keyword) {
				uni.getStorage({
					key: 'OldKeys',
					success: (res) => {
						console.log(res.data);
						var OldKeys = JSON.parse(res.data);
						var findIndex = OldKeys.indexOf(keyword);
						if (findIndex == -1) {
							OldKeys.unshift(keyword);
						} else {
							OldKeys.splice(findIndex, 1);
							OldKeys.unshift(keyword);
						}
						//最多10个纪录
						OldKeys.length > 10 && OldKeys.pop();
						uni.setStorage({
							key: 'OldKeys',
							data: JSON.stringify(OldKeys)
						});
						this.oldKeywordList = OldKeys; //更新历史搜索
					},
					fail: (e) => {
						var OldKeys = [keyword];
						uni.setStorage({
							key: 'OldKeys',
							data: JSON.stringify(OldKeys)
						});
						this.oldKeywordList = OldKeys; //更新历史搜索
					}
				});
			}
		}
	}
</script>
<style>
	.content{background-color:rgb(242,242,242);}
	view{display:block;}
	.search-box {width:95%;background-color:rgb(242,242,242);padding:15upx 2.5%;display:flex;justify-content:space-between;}
	.search-box .mSearch-input-box{width: 100%;}
	.search-box .input-box {width:85%;flex-shrink:1;display:flex;justify-content:center;align-items:center;}
	.search-box .search-btn {width:15%;margin:0 0 0 2%;display:flex;justify-content:center;align-items:center;flex-shrink:0;font-size:28upx;color:#fff;background:linear-gradient(to right,#ff9801,#ff570a);border-radius:60upx;}
	.search-box .input-box>input {width:100%;height:60upx;font-size:32upx;border:0;border-radius:60upx;-webkit-appearance:none;-moz-appearance:none;appearance:none;padding:0 3%;margin:0;background-color:#ffffff;}
	.placeholder-class {color:#9e9e9e;}
	.search-keyword {width:100%;background-color:rgb(242,242,242);}
	.keyword-list-box {height:calc(100vh - 110upx);padding-top:10upx;border-radius:20upx 20upx 0 0;background-color:#fff;}
	.keyword-entry-tap {background-color:#eee;}
	.keyword-entry {width:94%;height:80upx;margin:0 3%;font-size:30upx;color:#333;display:flex;justify-content:space-between;align-items:center;border-bottom:solid 1upx #e7e7e7;}
	.keyword-entry image {width:60upx;height:60upx;}
	.keyword-entry .keyword-text,.keyword-entry .keyword-img {height:80upx;display:flex;align-items:center;}
	.keyword-entry .keyword-text {width:90%;}
	.keyword-entry .keyword-img {width:10%;justify-content:center;}
	.keyword-box {height:calc(100vh - 110upx);border-radius:20upx 20upx 0 0;background-color:#fff;}
	.keyword-box .keyword-block {padding:10upx 0;}
	.keyword-box .keyword-block .keyword-list-header {width:94%;padding:10upx 3%;font-size:27upx;color:#333;display:flex;justify-content:space-between;}
	.keyword-box .keyword-block .keyword-list-header image {width:40upx;height:40upx;}
	.keyword-box .keyword-block .keyword {width:94%;padding:3px 3%;display:flex;flex-flow:wrap;justify-content:flex-start;}
	.keyword-box .keyword-block .hide-hot-tis {display:flex;justify-content:center;font-size:28upx;color:#6b6b6b;}
	.keyword-box .keyword-block .keyword>view {display:flex;justify-content:center;align-items:center;border-radius:60upx;padding:0 20upx;margin:10upx 20upx 10upx 0;height:60upx;font-size:28upx;background-color:rgb(242,242,242);color:#6b6b6b;}

	.list .item {
	    text-decoration: none;
	    color: #9b9b9b;
	}
	.cardlist .item {
	    text-decoration: none;
	    color: #9b9b9b;
	}
	.grid .item {
	    text-decoration: none;
	    color: #9b9b9b;
	}
	.list .item, .cardlist .item {
	    display: block;
	    padding: 40rpx 4%;
	    overflow: hidden;
	    position: relative;
	}
	.list .item .cover, .cardlist .item .cover {
	    float: left;
	    margin-right: 30rpx;
	    width: 200rpx;
	    min-height: 200rpx;
	}
	.list .item {
	    text-decoration: none;
	    color: #9b9b9b;
	}
	.list .item .img-show {
	    opacity: 1;
		width: 100%;
	}
	.list .item .info, .cardlist .item .info {
	    overflow: hidden;
	}
	.list .h3, .list .h4, .list .p {
	    margin: 0;
	}
	.list .item .h4, .cardlist .item .h4 {
	    font-size: 24rpx;
	    padding-bottom: 10rpx;
	}
	.list .item .h3, .cardlist .item .h3 {
	    font-size: 34rpx;
	    padding: 0 0 10rpx;
	    color: #494949;
	}
	.list .item .rank, .cardlist .item .rank {
	    font-size: 24rpx;
	}
	.list .item .rank, .cardlist .item .rank {
	    font-size: 24rpx;
		line-height: 40rpx;
	}
	.list .item .meta, .list .item .star, .cardlist .item .meta, .cardlist .item .star {
	    font-size: 24rpx;
		line-height: 40rpx;
	}
	.list .item .meta, .cardlist .item .meta {
	    padding-top: 20rpx;
		line-height: 40rpx;
	}
	.list .item::after, .cardlist .item::after {
	    left: 0;
	    bottom: 0;
	    width: 100%;
	    height: 2rpx;
	    background: #ccc;
	    -webkit-transform: scaleY(0.5);
	    content: '';
	    position: absolute;
	    -webkit-transform-origin: 0 bottom;
	}
	
	.grid {
	    padding: 20px 0;
	    margin-left: auto;
	    margin-right: auto;
	    max-width: 660px;
	    overflow: hidden;
	    box-sizing: border-box;
	}
	.grid .item {
	    float: left;
	    box-sizing: border-box;
	    width: 33.33333%;
	    padding-left: 4%;
	    padding-right: 4%;
	    margin-bottom: 20px;
	    overflow: hidden;
		color: #9b9b9b;
	}
	.grid .item .cover {
	    min-height: 87px;
	    overflow: hidden;
	    position: relative;
	}
	.grid .ratio1_1, .grid .ratio3_4 {
	    position: relative;
	}
	.grid .ratio3_4:before {
	    padding-top: 143%;
	}
	.grid .ratio1_1:before, .grid .ratio3_4:before {
	    content: "";
	    display: block;
	    padding-top: 100%;
	}
	.grid .item .image {
	    display: block;
	    position: absolute;
	    left: -100%;
	    right: -100%;
	    top: -100%;
	    bottom: -100%;
	    margin: auto;
	}
	.grid .item .info {
	    height: 45px;
	    overflow: hidden;
	}
	.grid .ratio1_1:before, .grid .ratio3_4:before {
	    content: "";
	    display: block;
	    padding-top: 100%;
	}
	.grid .ratio3_4:before {
	    padding-top: 143%;
	}
	.grid .item .h4, .grid .item .cite, .grid .item .meta {
	    display: none;
	}
	.grid .item .h3 {
	    font-size: 26rpx;
	    font-weight: normal;
	    padding: 10rpx 0 0;
	    color: #494949;
	    text-align: center;
	    overflow: hidden;
	    text-overflow: ellipsis;
	    display: -webkit-box;
	    -webkit-line-clamp: 1;
	    -webkit-box-orient: vertical;
	}
	.grid .item .rank {
	    height: 32rpx;
	    font-size: 24rpx;
	    padding-top: 6rpx;
	    text-align: center;
	}
	.grid .item .h4, .grid .item .cite, .grid .item .meta {
	    display: none;
	}
	.list .item .cite, .cardlist .item .cite {
	    font-size: 26rpx;
	    margin-top: 28rpx;
	    line-height: 36rpx;
	    overflow: hidden;
	    text-overflow: ellipsis;
	    display: -webkit-box;
	    -webkit-line-clamp: 3;
	    -webkit-box-orient: vertical;
	}
	
	.list .item .cover, .cardlist .item .cover {
	    float: left;
	    margin-right: 15px;
	    width: 100px;
	    min-height: 100px;
	}
	.list .item .cover .img, .cardlist .item .cover .img {
	    width: 100%;
	}
	.list .item .info, .cardlist .item .info {
	    overflow: hidden;
	}
	.list .item .h4, .cardlist .item .h4 {
	    font-size: 24rpx;
	    padding-bottom: 10rpx;
	}
	.list .item .h3, .cardlist .item .h3 {
	    font-size: 34rpx;
	    padding: 0 0 15rpx;
	    color: #494949;
	}
	.list .item .rank, .cardlist .item .rank {
	    font-size: 24rpx;
	}
	.list .item .meta, .list .item .star, .cardlist .item .meta, .cardlist .item .star {
	    font-size: 24rpx;
	}
	.list .item .meta, .cardlist .item .meta {
	    padding-top: 10rpx;
	}
	.list .item .cite, .cardlist .item .cite {
	    font-size: 26rpx;
	    margin-top: 28rpx;
	    line-height: 36rpx;
	    overflow: hidden;
	    text-overflow: ellipsis;
	    display: -webkit-box;
	    -webkit-line-clamp: 3;
	    -webkit-box-orient: vertical;
	}
	.list .item .cite {
	    font-style: normal;
	}
	.list .item .rank, .cardlist .item .rank {
	    font-size: 24rpx;
	}
</style>
